<template>
  <view class="register-container">
    <!-- 导航栏 -->
    <uni-nav-bar title="注册" left-icon="back" @click-left="goBack" fixed />

    <scroll-view class="scroll-content" scroll-y>
      <!-- 步骤指示器 -->
      <view class="steps-indicator">
        <view
          class="step-item"
          :class="{ active: currentStep >= 1, completed: currentStep > 1 }"
        >
          <view class="step-circle">
            <text class="step-num">{{ currentStep > 1 ? "✓" : "1" }}</text>
          </view>
          <text class="step-label">选择创客</text>
        </view>

        <view class="step-line" :class="{ active: currentStep > 1 }"></view>

        <view class="step-item" :class="{ active: currentStep >= 2 }">
          <view class="step-circle">
            <text class="step-num">2</text>
          </view>
          <text class="step-label">填写信息</text>
        </view>
      </view>

      <!-- 步骤1: 选择创客 -->
      <view v-if="currentStep === 1" class="form-content">
        <!-- 工号输入 -->
        <view class="input-section">
          <view class="input-row">
            <input
              class="input"
              v-model="workNumber"
              placeholder="请输入工号/邀请码/手机号进行查询"
              placeholder-class="placeholder"
            />
            <view
              class="search-btn"
              :class="{ disabled: searchLoading }"
              @click="handleSearch"
            >
              <uni-icons
                v-if="!searchLoading"
                type="search"
                size="16"
                color="#fff"
              />
              <uni-icons
                v-else
                type="loop"
                size="16"
                color="#fff"
                class="loading-icon"
              />
              <text class="btn-text">{{
                searchLoading ? "查询中" : "查询"
              }}</text>
            </view>
          </view>
        </view>

        <!-- 查询结果 -->
        <view v-if="creatorInfo" class="result-section">
          <view class="result-content">
            <view class="result-header">
              <text class="result-name">{{ creatorInfo.name }}</text>
              <text class="result-phone-hidden">{{
                creatorInfo.phoneHidden
              }}</text>
            </view>
            <view class="result-maker-no">工号：{{ creatorInfo.makerNo }}</view>
            <view class="result-invite-code">
              <text class="code-label">邀请码：</text>
              <text class="code-value">{{ creatorInfo.inviteCode }}</text>
            </view>
          </view>
          <view class="result-action">
            <view
              v-if="!isCreatorBound"
              class="add-btn"
              @click="handleBindCreator"
            >
              <uni-icons type="plus" size="20" color="#fff" />
            </view>
            <view v-else class="delete-btn" @click="handleUnbindCreator">
              <uni-icons type="trash" size="20" color="#fff" />
            </view>
          </view>
        </view>

        <!-- 已绑定的创客信息 -->
        <view v-if="isCreatorBound && boundCreatorInfo" class="bound-section">
          <view class="bound-title">已选择创客</view>
          <view class="bound-card">
            <!-- 删除按钮 -->
            <view class="bound-delete-btn" @click="handleUnbindCreator">
              <uni-icons type="trash" size="18" color="#ff4444" />
            </view>

            <view class="bound-header">
              <text class="bound-name">{{ boundCreatorInfo.name }}</text>
              <text class="bound-phone">{{
                boundCreatorInfo.phoneHidden
              }}</text>
            </view>
            <view class="bound-maker-no"
              >工号：{{ boundCreatorInfo.makerNo }}</view
            >
            <view class="bound-code">
              <text class="bound-code-label">邀请码：</text>
              <text class="bound-code-value">{{
                boundCreatorInfo.inviteCode
              }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 步骤2: 填写注册信息 -->
      <view v-if="currentStep === 2" class="form-content">
        <view class="section-title">账号信息</view>

        <!-- 手机号 -->
        <view class="form-item required">
          <view class="form-label">手机号</view>
          <view class="form-value">
            <input
              class="form-input"
              v-model="formData.mobile"
              type="number"
              maxlength="11"
              placeholder="请输入手机号"
            />
          </view>
        </view>

        <!-- 验证码 -->
        <view class="form-item required">
          <view class="form-label">验证码</view>
          <view class="form-value code-row">
            <input
              class="form-input"
              v-model="formData.code"
              type="number"
              maxlength="6"
              placeholder="请输入验证码"
            />
            <view
              class="send-code-btn"
              :class="{ disabled: codeCountdown > 0 || !canSendCode }"
              @click="sendCode"
            >
              {{ codeText }}
            </view>
          </view>
        </view>

        <!-- 密码 -->
        <view class="form-item required">
          <view class="form-label">登录密码</view>
          <view class="form-value">
            <input
              class="form-input"
              v-model="formData.password"
              :type="showPassword ? 'text' : 'password'"
              placeholder="请设置登录密码（6-20位）"
            />
            <uni-icons
              :type="showPassword ? 'eye-filled' : 'eye-slash-filled'"
              size="20"
              color="#999"
              @click="togglePassword"
            />
          </view>
        </view>

        <!-- 确认密码 -->
        <view class="form-item required">
          <view class="form-label">确认密码</view>
          <view class="form-value">
            <input
              class="form-input"
              v-model="confirmPassword"
              :type="showConfirmPassword ? 'text' : 'password'"
              placeholder="请再次输入密码"
            />
            <uni-icons
              :type="showConfirmPassword ? 'eye-filled' : 'eye-slash-filled'"
              size="20"
              color="#999"
              @click="toggleConfirmPassword"
            />
          </view>
        </view>

        <!-- 创客信息展示 -->
        <view class="section-title">推荐创客</view>
        <view class="creator-info-card">
          <view class="creator-row">
            <text class="creator-label">姓名：</text>
            <text class="creator-value">{{ boundCreatorInfo?.name }}</text>
          </view>
          <view class="creator-row">
            <text class="creator-label">工号：</text>
            <text class="creator-value">{{ boundCreatorInfo?.makerNo }}</text>
          </view>
          <view class="creator-row">
            <text class="creator-label">邀请码：</text>
            <text class="creator-value highlight">{{
              boundCreatorInfo?.inviteCode
            }}</text>
          </view>
        </view>
      </view>

      <!-- 底部按钮 -->
      <view class="bottom-btn-container">
        <uni-button v-if="currentStep > 1" class="prev-btn" @click="handlePrev">
          上一步
        </uni-button>
        <uni-button
          class="next-btn"
          type="primary"
          @click="handleNext"
          :loading="submitLoading || loginLoading"
        >
          {{ currentStep === 2 ? "提交注册" : "下一步" }}
        </uni-button>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import { useRequest } from "ahooks-vue";
import {
  getCreatorInfo,
  sendCode as sendCodeApi,
  registerByCode,
  loginByAccount,
} from "@/api/user";
import { encryptPassword } from "@/utils/crypto";
import { useUserStore } from "@/store/modules/user";

// 使用 Pinia store
const userStore = useUserStore();

// 当前步骤
const currentStep = ref(1);
// 工号
const workNumber = ref("");
// 创客信息
const creatorInfo = ref(null);
// 已绑定的创客信息
const boundCreatorInfo = ref(null);
// 是否已绑定创客
const isCreatorBound = ref(false);
// 验证码倒计时
const codeCountdown = ref(0);
// 显示密码
const showPassword = ref(false);
const showConfirmPassword = ref(false);
// 确认密码
const confirmPassword = ref("");

// 表单数据
const formData = ref({
  mobile: "", // 手机号
  code: "", // 验证码
  password: "", // 密码
  invitationCode: "", // 邀请码
  sharePerId: "", // 分享者Id
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 查询创客信息
const { run: getCreatorInfoRun, loading: searchLoading } = useRequest(
  (params) => getCreatorInfo(params),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("创客信息查询成功：", response);
      const data = response.data;
      if (data) {
        // 处理手机号脱敏
        const phone = data.mobile || "";
        const phoneHidden =
          phone.length >= 11
            ? phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2")
            : phone;

        creatorInfo.value = {
          name: data.nickname || "",
          phone: phone,
          phoneHidden: phoneHidden,
          makerNo: data.makerNo || "",
          inviteCode: data.inviteCode || "",
          userId: data.userId || "",
        };

        uni.showToast({
          title: "查询成功",
          icon: "none",
        });
      } else {
        creatorInfo.value = null;
        uni.showToast({
          title: "未找到该工号对应的创客",
          icon: "none",
        });
      }
    },
    onError: (error) => {
      console.error("查询创客信息失败：", error);
      creatorInfo.value = null;
      uni.showToast({
        title: error.message || "查询失败，请重试",
        icon: "none",
      });
    },
  }
);

// 查询工号/邀请码/手机号
const handleSearch = () => {
  if (!workNumber.value.trim()) {
    uni.showToast({
      title: "请输入工号/邀请码/手机号",
      icon: "none",
    });
    return;
  }

  const searchValue = workNumber.value.trim();

  getCreatorInfoRun({
    makerNo: searchValue,
    inviteCode: searchValue,
    mobile: searchValue,
  });
};

// 绑定创客
const handleBindCreator = () => {
  if (!creatorInfo.value) return;

  // 绑定邀请码和分享者ID
  formData.value.invitationCode = creatorInfo.value.inviteCode;
  formData.value.sharePerId = creatorInfo.value.userId;
  boundCreatorInfo.value = { ...creatorInfo.value };
  isCreatorBound.value = true;

  // 清空查询结果和工号
  creatorInfo.value = null;
  workNumber.value = "";

  uni.showToast({
    title: "绑定成功",
    icon: "none",
  });
};

// 解绑创客
const handleUnbindCreator = () => {
  uni.showModal({
    title: "提示",
    content: "确定要解绑该创客吗？",
    confirmColor: "#ff8c00",
    success: (res) => {
      if (res.confirm) {
        formData.value.invitationCode = "";
        formData.value.sharePerId = "";
        boundCreatorInfo.value = null;
        isCreatorBound.value = false;

        uni.showToast({
          title: "已解绑",
          icon: "none",
        });
      }
    },
  });
};

// 是否可以发送验证码
const canSendCode = computed(() => {
  return formData.value.mobile.length === 11;
});

// 验证码按钮文本
const codeText = computed(() => {
  return codeCountdown.value > 0 ? `${codeCountdown.value}s` : "发送验证码";
});

// 发送验证码
const sendCode = () => {
  if (codeCountdown.value > 0) return;

  if (!canSendCode.value) {
    uni.showToast({
      title: "请输入正确的手机号",
      icon: "none",
    });
    return;
  }

  // 调用发送验证码接口
  // 注意：发送验证码接口的参数是 ac（邮箱/手机号）
  sendCodeApi({
    ac: formData.value.mobile,
  })
    .then(() => {
      uni.showToast({
        title: "验证码已发送",
        icon: "none",
      });

      // 开始倒计时
      codeCountdown.value = 60;
      const timer = setInterval(() => {
        codeCountdown.value--;
        if (codeCountdown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    })
    .catch((error) => {
      uni.showToast({
        title: error.message || "发送失败，请重试",
        icon: "none",
      });
    });
};

// 切换密码显示
const togglePassword = () => {
  showPassword.value = !showPassword.value;
};

const toggleConfirmPassword = () => {
  showConfirmPassword.value = !showConfirmPassword.value;
};

// 下一步
const handleNext = () => {
  if (currentStep.value === 1) {
    // 步骤1验证
    if (!isCreatorBound.value) {
      uni.showToast({
        title: "请先选择创客",
        icon: "none",
      });
      return;
    }
    currentStep.value = 2;
  } else if (currentStep.value === 2) {
    // 步骤2验证并提交
    handleSubmit();
  }
};

// 上一步
const handlePrev = () => {
  if (currentStep.value > 1) {
    currentStep.value--;
  }
};

// 登录请求
const { run: loginRun, loading: loginLoading } = useRequest(
  (data) => loginByAccount(data),
  {
    manual: true,
    onSuccess: (result) => {
      console.log("登录成功：", result);

      // 使用 Pinia store 保存用户信息和 token
      if (result.data) {
        if (result.data.loginSubscribersVO) {
          userStore.setUserInfo(result.data.loginSubscribersVO);
        }
        if (result.data.token) {
          userStore.setToken(result.data.token);
        }
      }

      uni.showToast({
        title: "注册成功，自动登录中...",
        icon: "none",
      });

      // 登录成功后跳转到合作页面
      setTimeout(() => {
        uni.redirectTo({
          url: "/pages/login/partner/partner",
        });
      }, 1500);
    },
    onError: (error) => {
      console.error("自动登录失败：", error);
      uni.showToast({
        title: "注册成功，请手动登录",
        icon: "none",
      });

      // 登录失败，返回登录页
      setTimeout(() => {
        uni.redirectTo({
          url: "/pages/login/login",
        });
      }, 1500);
    },
  }
);

// 注册请求
const { loading: submitLoading, run: submitRegister } = useRequest(
  (data) => registerByCode(data),
  {
    manual: true,
    onSuccess: (result) => {
      console.log("注册成功：", result);

      // 注册成功后，使用手机号和密码自动登录
      const loginData = {
        me: formData.value.mobile, // 使用手机号登录
        password: encryptPassword(formData.value.password), // 加密密码
        type: 3, // 登录类型
      };

      uni.showToast({
        title: "注册成功",
        icon: "none",
      });

      // 延迟调用登录接口
      setTimeout(() => {
        loginRun(loginData);
      }, 1000);
    },
    onError: (error) => {
      console.error("注册失败：", error);
      uni.showToast({
        title: error.message || "注册失败，请重试",
        icon: "none",
      });
    },
  }
);

// 表单验证
const validateForm = () => {
  if (!formData.value.mobile) {
    uni.showToast({
      title: "请输入手机号",
      icon: "none",
    });
    return false;
  }

  if (formData.value.mobile.length !== 11) {
    uni.showToast({
      title: "请输入正确的手机号",
      icon: "none",
    });
    return false;
  }

  if (!formData.value.code) {
    uni.showToast({
      title: "请输入验证码",
      icon: "none",
    });
    return false;
  }

  if (!formData.value.password) {
    uni.showToast({
      title: "请设置登录密码",
      icon: "none",
    });
    return false;
  }

  if (
    formData.value.password.length < 6 ||
    formData.value.password.length > 20
  ) {
    uni.showToast({
      title: "密码长度为6-20位",
      icon: "none",
    });
    return false;
  }

  if (formData.value.password !== confirmPassword.value) {
    uni.showToast({
      title: "两次密码输入不一致",
      icon: "none",
    });
    return false;
  }

  if (!formData.value.invitationCode) {
    uni.showToast({
      title: "请选择创客",
      icon: "none",
    });
    return false;
  }

  return true;
};

// 提交注册
const handleSubmit = () => {
  if (!validateForm()) {
    return;
  }

  // 加密密码
  const encryptedPassword = encryptPassword(formData.value.password);
  if (!encryptedPassword) {
    uni.showToast({
      title: "密码加密失败，请重试",
      icon: "none",
    });
    return;
  }

  // 准备提交数据
  const submitData = {
    mobile: formData.value.mobile,
    code: parseInt(formData.value.code), // 转换为整数
    password: encryptedPassword,
    invitationCode: formData.value.invitationCode,
    sharePerId: formData.value.sharePerId,
  };

  console.log("提交注册数据：", {
    ...submitData,
    password: "***", // 隐藏密码
  });

  submitRegister(submitData);
};
</script>

<style scoped lang="scss">
.register-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.scroll-content {
  flex: 1;
  height: calc(100vh - 88rpx);
}

// 步骤指示器
.steps-indicator {
  background-color: #fff;
  padding: 40rpx 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 40rpx;
  margin-bottom: 20rpx;

  .step-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    flex: 0 0 auto;

    .step-circle {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      background-color: #f5f5f5;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 12rpx;
      transition: all 0.3s;

      .step-num {
        font-size: 24rpx;
        color: #999;
        font-weight: 500;
      }
    }

    .step-label {
      font-size: 24rpx;
      color: #999;
      text-align: center;
      white-space: nowrap;
    }

    &.active {
      .step-circle {
        background-color: #ff8c00;

        .step-num {
          color: #fff;
          font-weight: 600;
        }
      }

      .step-label {
        color: #333;
        font-weight: 500;
      }
    }

    &.completed {
      .step-circle {
        background-color: #ff8c00;

        .step-num {
          color: #fff;
        }
      }
    }
  }

  .step-line {
    flex: 0 0 80rpx;
    height: 2rpx;
    background-color: #e5e5e5;
    margin-bottom: 30rpx;
    transition: all 0.3s;

    &.active {
      background-color: #ff8c00;
    }
  }
}

// 表单内容
.form-content {
  background-color: #fff;
  padding: 40rpx;
  margin-bottom: 20rpx;
  padding-bottom: 160rpx;
}

// 输入部分
.input-section {
  margin-bottom: 32rpx;

  .input-row {
    display: flex;
    align-items: center;
    border: 1rpx solid #e5e5e5;
    border-radius: 8rpx;
    overflow: hidden;
    background-color: #f9f9f9;

    .input {
      flex: 1;
      height: 80rpx;
      padding: 0 24rpx;
      font-size: 28rpx;
      color: #333;
    }

    .placeholder {
      color: #999;
    }

    .search-btn {
      width: 140rpx;
      height: 80rpx;
      background-color: #ff8c00;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8rpx;
      transition: all 0.3s;

      .btn-text {
        font-size: 28rpx;
        color: #fff;
        font-weight: 500;
      }

      .loading-icon {
        animation: rotate 1s linear infinite;
      }

      &.disabled {
        opacity: 0.6;
        pointer-events: none;
      }
    }

    @keyframes rotate {
      from {
        transform: rotate(0deg);
      }
      to {
        transform: rotate(360deg);
      }
    }
  }
}

// 查询结果
.result-section {
  display: flex;
  padding: 32rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  margin-bottom: 40rpx;
  gap: 24rpx;

  .result-content {
    flex: 1;

    .result-header {
      display: flex;
      align-items: center;
      gap: 16rpx;
      margin-bottom: 16rpx;

      .result-name {
        font-size: 32rpx;
        color: #333;
        font-weight: 600;
      }

      .result-phone-hidden {
        font-size: 28rpx;
        color: #666;
      }
    }

    .result-maker-no {
      font-size: 24rpx;
      color: #999;
      margin-bottom: 16rpx;
      line-height: 1.5;
    }

    .result-invite-code {
      display: flex;
      align-items: center;
      padding: 16rpx;
      background-color: #fff;
      border-radius: 8rpx;

      .code-label {
        font-size: 28rpx;
        color: #666;
      }

      .code-value {
        font-size: 28rpx;
        color: #ff8c00;
        font-weight: 600;
      }
    }
  }

  .result-action {
    display: flex;
    flex-direction: column;
    justify-content: center;

    .add-btn,
    .delete-btn {
      width: 68rpx;
      height: 68rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s;

      &:active {
        opacity: 0.8;
        transform: scale(0.95);
      }
    }

    .add-btn {
      background-color: #ff8c00;
      box-shadow: 0 4rpx 12rpx rgba(255, 140, 0, 0.3);
    }

    .delete-btn {
      background-color: #ff4444;
      box-shadow: 0 4rpx 12rpx rgba(255, 68, 68, 0.3);
    }
  }
}

// 已绑定的创客信息
.bound-section {
  margin-bottom: 40rpx;

  .bound-title {
    font-size: 28rpx;
    color: #333;
    font-weight: 600;
    margin-bottom: 20rpx;
    padding-left: 16rpx;
    border-left: 6rpx solid #ff8c00;
  }

  .bound-card {
    position: relative;
    padding: 32rpx;
    background: linear-gradient(135deg, #fff8e1 0%, #ffe0b2 100%);
    border-radius: 12rpx;
    border: 2rpx solid #ff8c00;

    .bound-delete-btn {
      position: absolute;
      top: 20rpx;
      right: 20rpx;
      width: 48rpx;
      height: 48rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: rgba(255, 255, 255, 0.9);
      border-radius: 50%;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      transition: all 0.3s;

      &:active {
        opacity: 0.7;
        transform: scale(0.95);
        background-color: #fff;
      }
    }

    .bound-header {
      display: flex;
      align-items: center;
      gap: 16rpx;
      margin-bottom: 16rpx;

      .bound-name {
        font-size: 32rpx;
        color: #333;
        font-weight: 600;
      }

      .bound-phone {
        font-size: 28rpx;
        color: #666;
      }
    }

    .bound-maker-no {
      font-size: 24rpx;
      color: #999;
      margin-bottom: 16rpx;
      line-height: 1.5;
    }

    .bound-code {
      display: flex;
      align-items: center;
      padding: 16rpx;
      background-color: #fff;
      border-radius: 8rpx;

      .bound-code-label {
        font-size: 28rpx;
        color: #666;
      }

      .bound-code-value {
        font-size: 32rpx;
        color: #ff8c00;
        font-weight: 700;
      }
    }
  }
}

// 表单项
.form-item {
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f0f0f0;

  &.required {
    .form-label::before {
      content: "*";
      color: #ff4444;
      margin-right: 8rpx;
    }
  }

  .form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;
    font-weight: 500;
  }

  .form-value {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16rpx;

    .form-input {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }

    &.code-row {
      gap: 16rpx;

      .send-code-btn {
        flex-shrink: 0;
        padding: 16rpx 24rpx;
        background-color: #ff8c00;
        color: #fff;
        font-size: 24rpx;
        border-radius: 8rpx;
        white-space: nowrap;
        transition: all 0.3s;

        &.disabled {
          background-color: #ddd;
          color: #999;
          pointer-events: none;
        }

        &:active:not(.disabled) {
          opacity: 0.8;
        }
      }
    }
  }
}

.section-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 600;
  margin: 32rpx 0 24rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #ff8c00;
}

// 创客信息卡片
.creator-info-card {
  background-color: #f8f9fa;
  padding: 24rpx;
  border-radius: 12rpx;
  border-left: 4rpx solid #ff8c00;

  .creator-row {
    display: flex;
    align-items: center;
    padding: 12rpx 0;

    .creator-label {
      font-size: 28rpx;
      color: #666;
      width: 140rpx;
    }

    .creator-value {
      flex: 1;
      font-size: 28rpx;
      color: #333;

      &.highlight {
        color: #ff8c00;
        font-weight: 600;
      }
    }
  }
}

// 底部按钮
.bottom-btn-container {
  background-color: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 32rpx 40rpx;
  padding-bottom: calc(32rpx + env(safe-area-inset-bottom));
  display: flex;
  gap: 24rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05);

  .prev-btn,
  .next-btn {
    flex: 1;
    height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: 600;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;

    &::after {
      border: none;
    }
  }

  .prev-btn {
    background-color: #f5f5f5;
    color: #666;
  }

  .next-btn {
    background-color: #ff8c00;
    color: #fff;
  }
}
</style>
